<?php
/*
 * 汽车之家图片处理
 * @package    system
 * @author     Mark
 * @copyright  Copyright (c) 2013 ixdcw team
 * @version    $Id: 1db9a26afe7433da57e50b0c7a78ca2532c15323 $
 */
set_time_limit(0);
include '../../common.inc.php';
timer_start();
error_reporting(E_ALL ^ E_NOTICE);
$hd = new ImportLoop();
$hd->setAim('mysql:host=192.168.1.19;dbname=ixdcw_v11', 'root', 'xddlxdcw');
$hd->setSource('mysql:host=192.168.1.19;dbname=caiji', 'root', 'xddlxdcw');
$hd->setSourceInfo('picfolders', 'id', ' handle=0');
$params = array(
	'maxid'        => isset($_GET['maxid']) ? $_GET['maxid'] : 0,
	'id'           => isset($_GET['id']) && !empty($_GET['id']) ? $_GET['id'] : 0,
	'startTime'    => isset($_GET['startTime']) ? $_GET['startTime'] : time(),
	'limit'        => 1,
	'interval'     => 0,
	'debug'        => 'xddl',
	'sourceFolder' => '//192.168.1.89/autopic',
	'aimFolder'    => 'W:/aimPic',
	'markHeight'   => 20,
	'jpegQuality'   => 85,
);

$hd->initParams($params);

$sql = 'select * from ' . $hd->getSourceTable() . ' where id>' . $hd->getParam('id') . ' and handle=0 order by id ASC limit ' . $hd->getParam('limit');

$result = $hd->getDbSource()->query($sql);
$rs     = $result->fetchAll();

if (!$rs) {
	$hd->times();
	$hd->end();
} else {
	foreach ($rs as $k => $v) {
		$hd->setParam('id', $v['id']); // set id
		$sqlUpdate    = Sql::update($hd->getSourceTable(), 'handle=1', "id={$v['id']}");
		$sourceFolder = $hd->getParam('sourceFolder') . str_replace('//', '/', $v['name']);
		$aimFolder    = $hd->getParam('aimFolder') . $v['name'];
		File::mkdir(Str::convert($aimFolder));
		$needHandle   = File::subFile(Str::convert($sourceFolder, 'utf8', 'gbk'));
		if (empty($needHandle)) {
			$hd->getDbSource()->query($sqlUpdate);
			$hd->times("当前处理ID:{$v['id']}, 空文件夹:{$sourceFolder}", 'warn');
			continue;
		} else {
			foreach ($needHandle as $file) {
				if (!Utils::isImage($file)){
					continue;
				}
				$aimFile = str_replace($hd->getParam('sourceFolder'), $hd->getParam('aimFolder'), $file);

				if (file_exists($aimFile)) {
					continue;
				} else {
					$info = getimagesize($file);
					try {
						$options = array(
							'jpegQuality' => $hd->getParam('jpegQuality'),
						);
						$thumb = PhpThumbFactory::create($file, $options);
						$thumb->crop(0, $hd->getParam('markHeight'), $info[0], $info[1] - $hd->getParam('markHeight')*2)
							->save($aimFile);
					} catch (Exception $e) {
						File::append('error_imageImport', Str::convert($e->getMessage(), 'gbk', 'utf-8'));
						continue;
					}
				}
			}
			File::append(__DIR__.'/time_picture', timer_end()."\t".count($needHandle));
			$hd->getDbSource()->query($sqlUpdate);
			$hd->times("当前处理ID:{$v['id']}, 文件夹:{$sourceFolder}完成");
		}
	}
}
echo $hd->start($hd->getParams());